<?php

namespace app\admin\service;

use app\model\Money;
use app\model\RechargeTemplate;
use app\model\Link;
use app\model\ResponsibilityPerson;
use app\model\PayRecord;
use think\facade\Db;
use app\model\RechargeLimitTemplate;
use app\model\RechargeLimitTemplateCompany;
use app\model\RechargeLimitTemplateVideo;
use app\model\Company;
use app\model\Videos;
use app\common\Error;
use app\model\CustomRechargeTemplate;

class MoneyService
{
    private $model;
    private $rechargeTemplateModel;
    private $linkModel;
    private $responsibilityPersonModel;
    private $payRecordModel;
    private $rechargeLimitTemplate;
    private $rechargeLimitTemplateCompany;
    private $rechargeLimitTemplateVideo;
    private $company;
    private $videos;
    private $customRechargeTemplateModel;

    public function __construct(Money $model, RechargeTemplate $rechargeTemplateModel, Link $linkModel, ResponsibilityPerson $responsibilityPersonModel, PayRecord $payRecordModel, RechargeLimitTemplate $rechargeLimitTemplate, RechargeLimitTemplateCompany $rechargeLimitTemplateCompany, RechargeLimitTemplateVideo $rechargeLimitTemplateVideo, Company $company, Videos $videos, CustomRechargeTemplate $customRechargeTemplateModel)
    {
        $this->model = $model;
        $this->rechargeTemplateModel = $rechargeTemplateModel;
        $this->linkModel = $linkModel;
        $this->responsibilityPersonModel = $responsibilityPersonModel;
        $this->payRecordModel = $payRecordModel;
        $this->rechargeLimitTemplate = $rechargeLimitTemplate;
        $this->rechargeLimitTemplateCompany = $rechargeLimitTemplateCompany;
        $this->rechargeLimitTemplateVideo = $rechargeLimitTemplateVideo;
        $this->company = $company;
        $this->videos = $videos;
        $this->customRechargeTemplateModel = $customRechargeTemplateModel;
    }

    // 获取充值列表
    public function rechargeSettingsList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $data = $this->model->getPagingDataByWhere(['is_delete' => 0], $page, $limit, 'id, name, label, display_object, original_currency, send_currency, sum_currency, send_title, recharge_price, platform_type, type, is_common,is_display', 'is_display desc,sort asc, id desc');
        return $data;
    }

    // 获取充值详情
    public function rechargeSettingsDetail($id)
    {
        $data = $this->model->getInfoById($id, 'id, name, label, display_object, original_currency, send_currency, sum_currency, send_title, sort, recharge_price, platform_type, type, is_common,is_display');
        return $data;
    }

    // 添加/编辑
    public function editRechargeSettings($params)
    {
        if (empty($params['id'])) {
            $params['created_at'] = time();
        } else {
            $params['updated_at'] = time();
            $data = $this->model->getInfoById($params['id'], 'is_common');
            // 公共配置不能修改成非公共配置
            if ($data['is_common'] == 1 && $data['is_common'] != $params['is_common']) {
                return ['message' => Error::PUBLIC_CANNOT_BE_MODIFIED_TO_NON_PUBLIC];
            }
        }

        $params['original_currency'] = $params['recharge_price'] * 100;
        $params['sum_currency'] = $params['original_currency'] + $params['send_currency'];

        $id = $this->model->edit($params);

        if (!$id) {
            return false;
        }

        return true;
    }

    // 删除充值设置
    public function deleteRechargeSettings($id)
    {
        $bool = $this->model->edit(['id' => $id, 'is_delete' => 1, 'updated_at' => time()]);

        if (!$bool) {
            return false;
        }

        return true;
    }

    // 获取充值模板数据列表
    public function rechargeTemplateList($params)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = $linkWhere = [];
        if (!empty($params['video_id'])) {
            $linkWhere[] = ['video_id', '=', $params['video_id']];
            $linkWhere[] = ['recharge_template_id', '<>', 0];

            // 按短剧统计
            $linkData = $this->linkModel->getDataByWhere($linkWhere, 'id, recharge_template_id');
            $linkIds = array_column($linkData, 'id');
            $rechargeTemplateIds = array_column($linkData, 'recharge_template_id');

            $where = ['id' => $rechargeTemplateIds];
        }
        //高中低面板筛选
        if (!empty($params['type'])) {
            $where['type'] = $params['type'];
        }

        // 公司搜索
        if (!empty($params['company_id'])) {
            $responsibilityPersonSer = $this->responsibilityPersonModel->getDataByWhere(['company_id' => $params['company_id']], 'id, is_distributor');

            $responsibilityPersonIdsSer = array_column($responsibilityPersonSer, 'id');

            if (!empty($responsibilityPersonSer[0]['is_distributor'])) {
                $responsibilityPersonSer = $this->responsibilityPersonModel->getDataByWhere(['pid' => $responsibilityPersonIdsSer], 'id');
                $responsibilityPersonIdsSer = array_column($responsibilityPersonSer, 'id');
            }

            $where[] = ['responsibility_person_id', 'in', $responsibilityPersonIdsSer];
        }


        $data = $this->rechargeTemplateModel->getPagingDataByWhere($where, $page, $limit, 'id, name, responsibility_person_id, created_at');

        $responsibilityPersonIds = array_column($data['data'], 'responsibility_person_id');

        // 获取负责人数据
        $responsibilityPersonData = $this->responsibilityPersonModel->getDataByWhere(['id' => $responsibilityPersonIds], 'id, name');
        $responsibilityPerson = array_column($responsibilityPersonData, 'name', 'id');

        // 获取使用的链接
        if ($linkWhere) {
            $useLink = [];
            foreach ($linkData as $key => $value) {
                $useLink[$value['recharge_template_id']][] = $value['id'];
            }
        } else {
            $rechargeTemplateIds = array_column($data['data'], 'id');
            $linkData = $this->linkModel->getDataByWhere(['recharge_template_id' => $rechargeTemplateIds], 'id, recharge_template_id');
            $linkIds = [];
            foreach ($linkData as $key => $value) {
                $useLink[$value['recharge_template_id']][] = $value['id'];
                $linkIds[] = $value['id'];
            }
        }

        // 获取充值数据
        $payRecordData = $this->payRecordModel->getInfo(['link_id' => $linkIds, 'status' => 1], 'link_id, uid, total_fee');
        $payRecord = [];
        foreach ($payRecordData as $key => $value) {
            $payRecord[$value['link_id']][] = $value;
        }

        // 组装数据
        foreach ($data['data'] as $key => $value) {
            $useLinkIds = empty($useLink[$value['id']]) ? [] : $useLink[$value['id']];
            $data['data'][$key]['link_ids'] = empty($useLink[$value['id']]) ? '' : implode(',', $useLink[$value['id']]);
            $uids = [];
            $recharge = 0;
            $rechargeNumber = 0;
            if (!empty($useLinkIds)) {
                foreach ($useLinkIds as $linkId) {
                    if (isset($payRecord[$linkId])) {
                        foreach ($payRecord[$linkId] as $item) {
                            $uids[] = $item['uid'];
                            $recharge += $item['total_fee'];
                            $rechargeNumber += 1;
                        }
                    }
                }
            }
            $rechargeUserNum = count(array_unique($uids));
            $data['data'][$key]['recharge_user_num'] = $rechargeUserNum;
            $rechargePrice = round($recharge, 2);
            $data['data'][$key]['recharge_price'] = $rechargePrice;
            $data['data'][$key]['per_capita_contribution'] = $rechargeUserNum == 0 ? 0 : round($rechargePrice / $rechargeUserNum, 2);
            $data['data'][$key]['recharge_number'] = $rechargeNumber;
            $data['data'][$key]['responsibility_person_name'] = $responsibilityPerson[$value['responsibility_person_id']];
        }

        return $data;
    }

    // 充值限制开关设置
    public function rechargeLimitSwitchSetting($params)
    {
        if (!empty($params['type']) && $params['type'] == 1) {
            $data = Db::name('recharge_limit_switch_setting')->field('id, start_charge_drama_series_limit, bottom_price_limit')->where(['id' => 1])->find();
            return $data;
        }
        $saveData = ['updated_at' => time()];
        // 开始收费集数限制：如果开启新剧开始投放算起3天内，开始收费集数不能设置在20集之后
        if (!empty($params['start_charge_drama_series_limit'])) {
            $saveData['start_charge_drama_series_limit'] = $params['start_charge_drama_series_limit'];
        }
        // 充值面板最低价限制：如果开启新剧开始投放算起3天内，最低价不能低于9.9
        if (!empty($params['bottom_price_limit'])) {
            $saveData['bottom_price_limit'] = $params['bottom_price_limit'];
        }
        $bool = Db::name('recharge_limit_switch_setting')->where(['id' => $params['id']])->update($saveData);

        if (!$bool) {
            return [];
        }
        $data = Db::name('recharge_limit_switch_setting')->field('id, start_charge_drama_series_limit, bottom_price_limit')->where(['id' => $params['id']])->find();
        return $data;
    }

    // 充值金额列表新增是否启用
    public function rechargeMoneySwitchSetting($params)
    {
        $saveData = ['updated_at' => time()];
        if (!empty($params['is_display']) && $params['is_display'] == 1) {
            $saveData['is_display'] = 1;
        } else {
            $saveData['is_display'] = 0;
        }

        $bool = Db::name('money')->where(['id' => $params['id']])->update($saveData);

        if (!$bool) {
            return false;
        }

        return true;
    }

    public function getRechargeTemplateLimit(array $params)
    {
        $id = (int)$params['id'];
        $rechargeName = (string)$params['recharge_name'];
        $page = (int)$params['page'];
        $limit = (int)$params['limit'];

        $limitData = $this->rechargeLimitTemplate->selectLimitByIdAndRechargeName(['id', 'recharge_name', 'recharge_day', 'recharge_amount', 'recharge_set'], $page, $limit, $id, $rechargeName);

        if (empty($limitData)) {
            return [
                'data' => $limitData,
                'count' => 0,
                'total_count' => 0
            ];
        }

        $formatData = [];

        foreach ($limitData as $limit) {
            $formatData[] = [
                'id' => $limit['id'],
                'recharge_name' => $limit['recharge_name'],
                'recharge_day' => $limit['recharge_day'],
                'recharge_amount' => $limit['recharge_amount'],
                'recharge_set' => $limit['recharge_set'],
                'recharge_white' => !empty($limit['rechargeLimitTemplateCompany']) ? $limit['rechargeLimitTemplateCompany'] : []
            ];
        }

        $totalCount = $this->rechargeLimitTemplate->selectLimitByIdRechargeNameCount($id, $rechargeName);

        return [
            'data' => $formatData,
            'count' => count($limitData),
            'total_count' => $totalCount
        ];
    }

    public function addRechargeTemplateLimit(array $params)
    {
        $rechargeName = (string)$params['recharge_name'];
        $rechargeDay = (int)$params['recharge_day'];
        $rechargeAmount = (float)$params['recharge_amount'];
        $rechargeSet = (int)$params['recharge_set'];
        $rechargeWhiteIdStr = (string)$params['recharge_white_ids'];

        $rechargeWhiteIds = explode(',', $rechargeWhiteIdStr);

        $limitData = $this->rechargeLimitTemplate->selectFirstRechargeName(['id'], $rechargeName);

        if (!empty($limitData)) {
            return ['message' => '已存在重复的充值限制名称'];
        }

        Db::startTrans();

        try {
            $insertLimitData = [
                'recharge_name' => $rechargeName,
                'recharge_day' => $rechargeDay,
                'recharge_amount' => $rechargeAmount,
                'recharge_set' => $rechargeSet,
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s')
            ];

            $rechargeLimitId = $this->rechargeLimitTemplate->insertGetId($insertLimitData);

            $insertLimitCompanyData = [];

            $baseCompanyData = $this->company->getDataByWhere(['is_distributor' => 0], 'id');

            if (!empty($baseCompanyData)) {
                foreach ($baseCompanyData as $baseCompany) {
                    $insertLimitCompanyData[$baseCompany['id']] = [
                        'recharge_limit_template_id' => $rechargeLimitId,
                        'company_id' => $baseCompany['id'],
                    ];
                }
            }

            if (!empty($rechargeWhiteIds)) {
                $whiteCompanyData = $this->company->selectInId(['id'], $rechargeWhiteIds);
                if (!empty($whiteCompanyData)) {
                    foreach ($whiteCompanyData as $whiteCompany) {
                        $insertLimitCompanyData[$whiteCompany['id']] = [
                            'recharge_limit_template_id' => $rechargeLimitId,
                            'company_id' => $whiteCompany['id'],
                        ];
                    }
                }
            }

            $this->rechargeLimitTemplateCompany->insertAll($insertLimitCompanyData);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return ['message' => '系统异常请稍后再试'];
        }
    }

    public function deleteRechargeTemplateLimit(array $params)
    {
        $id = (int)$params['id'];

        $limitData = $this->rechargeLimitTemplate->selectFirstById(['id'], $id);

        if (empty($limitData)) {
            return ['message' => '获取充值限制模板失败'];
        }

        if (!empty($limitData['rechargeLimitTemplateWhite'])) {
            return ['message' => '当前充值限制模板下还有存在的白名单'];
        }

        $this->rechargeLimitTemplate->deleteByid($id);
    }

    public function updateRechargeTemplateLimit(array $params)
    {
        $id = (int)$params['id'];
        $rechargeWhiteIdStr = (string)$params['recharge_white_ids'];

        $rechargeWhiteIds = explode(',', $rechargeWhiteIdStr);

        $limitData = $this->rechargeLimitTemplate->selectFirstById(['id'], $id);

        if (empty($limitData)) {
            return ['message' => '获取充值限制模板失败'];
        }

        $insertLimitWhiteData = [];

        $whiteCompanyData = $this->company->selectInId(['id'], $rechargeWhiteIds);

        if (!empty($whiteCompanyData)) {
            foreach ($whiteCompanyData as $whiteCompany) {
                $insertLimitWhiteData[$whiteCompany['id']] = [
                    'recharge_limit_template_id' => $id,
                    'company_id' => $whiteCompany['id'],
                ];
            }
        }

        Db::startTrans();

        try {

            $this->rechargeLimitTemplateCompany->deleteByRechargeLimitTemplateId($id);

            if (!empty($insertLimitWhiteData)) {
                $this->rechargeLimitTemplateCompany->insertAll($insertLimitWhiteData);
            }

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return ['message' => '系统异常请稍后再试'];
        }
    }

    public function updateRechargeTemplateLimitVideo(array $params)
    {
        $id = (int)$params['id'];
        $videoId = (int)$params['video_id'];

        $insertLimitWhiteData = [];

        $videoData = $this->videos->getInfoById($videoId);

        if (empty($videoData)) {
            return ['message' => '获取短剧信息失败'];
        }

        if (!empty($id)) {
            $limitData = $this->rechargeLimitTemplate->selectFirstById(['id'], $id);

            if (empty($limitData)) {
                return ['message' => '获取充值限制模板失败'];
            }

            $insertLimitWhiteData[] = [
                'recharge_limit_template_id' => $id,
                'video_id' => $videoId,
            ];
        }

        Db::startTrans();

        try {

            $this->rechargeLimitTemplateVideo->deleteByVideoId($videoId);

            if (!empty($insertLimitWhiteData)) {
                $this->rechargeLimitTemplateVideo->insertAll($insertLimitWhiteData);
            }

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return ['message' => '系统异常请稍后再试'];
        }
    }

    public function getRechargeTemplateLimitDetail(array $params)
    {
        $id = (int)$params['id'];

        $limitData = $this->rechargeLimitTemplate->selectFirstById(['id', 'recharge_name', 'recharge_day', 'recharge_amount', 'recharge_set'], $id);

        if (empty($limitData)) {
            return ['message' => '获取充值限制模板失败'];
        }

        $limitData['recharge_white'] = !empty($limitData['rechargeLimitTemplateCompany']) ? $limitData['rechargeLimitTemplateCompany'] : [];

        unset($limitData['rechargeLimitTemplateCompany']);

        return $limitData;
    }

    public function getRechargeTemplateLimitVideoDetail(array $params)
    {
        $videoId = (int)$params['video_id'];

        $videoLimitData = $this->rechargeLimitTemplateVideo->selectWithTemplateFirstByVideoId(['video_id', 'recharge_limit_template_id'], $videoId);

        if (empty($videoLimitData)) {
            return ['message' => '获取充值限制模板失败'];
        }

        $videoLimitData['recharge_template'] = !empty($videoLimitData['rechargeLimitTemplate']) ? $videoLimitData['rechargeLimitTemplate'] : [];

        unset($videoLimitData['rechargeLimitTemplate']);

        return $videoLimitData;
    }

    // 获取自定义充值模板下拉列表
    public function getRechargeTemplateSelectData($videoId)
    {
        $data = $this->customRechargeTemplateModel->getDataByWhere(['video_id' => $videoId, 'status' => 1], 'id, name');
        return $data;
    }

    // 获取充值限制模板下拉列表
    public function getRechargeLimitTemplateSelectData()
    {
        return $this->rechargeLimitTemplate->getDataByWhere([], 'id, recharge_name as name');
    }
}
